<template>
    <div class="edu-page-warp">
        <condition-card @reset="reset" @search="searchData">
            <el-form :model="queryForm" label-position="left" label-width="80px">
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item :label="$t('minor.major.minorGrade')+'：'">
                            <el-date-picker
                                v-model="queryForm.grade"
                                type="year"
                                clearable
                                value-format="yyyy"
                                style="width: 100%;"
                                :placeholder="$t('minor.tip.choose')"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('minor.course.advancedLevel')+'：'">
                            <el-select
                                v-model="queryForm.advancedLevel"
                                clearable
                                style="width: 100%;"
                            >
                                <el-option
                                    v-for="item in options.advancedLevel"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('minor.table.startTime')+'：'">
                            <el-date-picker
                                style="width: 100%;"
                                v-model="queryForm.startTime"
                                value-format="timestamp"
                                type="date"
                                clearable
                                :placeholder="$t('minor.tip.selectDate')"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24" style="height: 50px;">
                    <el-col :span="8">
                        <el-form-item :label="$t('minor.table.endTime')+'：'">
                            <el-date-picker
                                style="width: 100%;"
                                v-model="queryForm.endTime"
                                value-format="timestamp"
                                type="date"
                                clearable
                                :placeholder="$t('minor.tip.selectDate')"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </condition-card>

        <el-card shadow="never" body-style="padding: 24px;">
            <div
                class="edu-page-title mg-top"
            >{{$t("minor.culturePermission.culturePermissionTitle")}}</div>
            <div class="edu-opertion-bar">
                <div class="float-right">
                    <el-button
                        @click="batchDeleteAuthPushData"
                        type="danger"
                    >{{$t("message.delete")}}</el-button>
                    <el-button @click="showAddDialog" type="primary">{{$t("message.add")}}</el-button>
                </div>
            </div>
            <EduTable
                @page-change="pageChange"
                :data="tableData.list"
                :total="tableData.total_"
                @selection-change="handleSelectionChange"
            >
                <el-table-column
                    prop="grade"
                    :label="$t('minor.major.minorGrade')"
                    min-width="100"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    prop="advancedLevelName"
                    :label="$t('minor.course.advancedLevel')"
                    min-width="100"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    prop="startTime"
                    show-overflow-tooltip
                    :label="$t('minor.table.startTime')"
                    min-width="160"
                ></el-table-column>
                <el-table-column
                    prop="endTime"
                    :label="$t('minor.table.endTime')"
                    min-width="160"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column :label="$t('message.operating')" min-width="120">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            @click="editPermission(scope.row)"
                            size="mini"
                        >{{$t("message.edit")}}</el-button>
                        <el-button
                            type="text"
                            @click="deletePermission(scope.row)"
                            size="mini"
                        >{{$t("message.delete")}}</el-button>
                    </template>
                </el-table-column>
            </EduTable>
        </el-card>
        <el-dialog
            :title="dialogTitle"
            width="40%"
            :visible.sync="showDialog"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <el-form
                :model="postForm"
                label-position="left"
                label-width="80px"
                ref="postForm"
                :rules="rules"
            >
                <el-row :gutter="24">
                    <el-col :span="24">
                        <el-form-item :label="$t('minor.major.minorGrade')" prop="grade">
                            <el-select v-model="postForm.grade" style="width: 100%;">
                                <el-option
                                    v-for="item in options.grade"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="24">
                        <el-form-item label="进阶层次" prop="advancedLevel">
                            <el-select v-model="postForm.advancedLevel" style="width: 100%;">
                                <el-option
                                    v-for="item in options.advancedLevel"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="24">
                        <el-form-item :label="$t('message.startDate')" prop="startTime">
                            <el-date-picker
                                style="width: 100%;"
                                v-model="postForm.startTime"
                                type="date"
                                format="yyyy-MM-dd"
                                placeholder="选择日期"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="24">
                        <el-form-item :label="$t('message.endDate')" prop="endTime">
                            <el-date-picker
                                style="width: 100%;"
                                v-model="postForm.endTime"
                                type="date"
                                format="yyyy-MM-dd"
                                placeholder="选择日期"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="24" style="text-align:right;margin-top:10px">
                        <el-button @click="cancel" type="button">取消</el-button>
                        <el-button @click="save" type="primary">保存</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
import bus from "common/src/utils/bus";
import { queryDic, findTrainingLevelByProjId } from "common/src/api/dictionary";
import { queryList } from "common/src/api/culture/culturePlan";
import { queryAdvancedLevel } from "common/src/api/minor/collegemajor";
import {
    queryCulturePlanPermission,
    insertCulturePlanPermission,
    modifyCulturePlanPermission,
    deleteCulturePlanPermission,
    batchDeleteCulturePlanPermission
} from "common/src/api/minor/culturePlanPermission";
import UTILS from "common/src/utils/utils";
import * as INDEX from "common/src/utils/index";
export default {
    data() {
        return {
            queryForm: {
                grade: "",
                advancedLevel: "",
                startTime: "",
                endTime: "",
                pageSize: 20,
                pageNum: 1,
                total: 0
            },
            selectData: [],
            postForm: {
                grade: "",
                advancedLevel: "",
                startTime: "",
                endTime: "",
                id: null
            },
            options: {
                grade: [],
                advancedLevel: [],
                college: [],
                relationSelectCourse: []
            },
            page: {
                pageNum: 1,
                pageSize: 20
            },
            tableData: {
                list: [],
                total_: 0
            },
            showDialog: false,
            dialogTitle: "",
            showTerm: true,
            rules: {
                grade: [
                    {
                        required: true,
                        message: "请选择年级",
                        trigger: "change"
                    }
                ],
                advancedLevel: [
                    {
                        required: true,
                        message: "请选择进阶层次",
                        trigger: "change"
                    }
                ],
                startTime: [
                    {
                        required: true,
                        message: "请选择开始时间",
                        trigger: "blur"
                    }
                ],
                endTime: [
                    {
                        required: true,
                        message: "请选择结束时间",
                        trigger: "blur"
                    }
                ]
            }
        };
    },
    mounted: function() {
        if (!this.$checkMinor()) return;
        this.init();
        this.initProjId();
        this.initadvancedLevelOptions();
        this.initPlanPermissionData();
    },
    methods: {
        initProjId() {
            let currentUser =
                (this.$store.state.session && this.$store.state.session.user) ||
                JSON.parse(localStorage.getItem("user"));
            this.queryForm.projId = currentUser.currentManageDptId;
        },
        initadvancedLevelOptions() {
            let params = {
                isOnCampus: "0"
            };
            this.options["advancedLevel"] = [];
            queryAdvancedLevel(params).then(res => {
                if (res.code == 200) {
                    for (let key = 0; key < res.data.length; key++) {
                        this.options["advancedLevel"].push({
                            value: res.data[key].advancedLevelCode,
                            label: res.data[key].advancedLevelName
                        });
                    }
                }
            });
        },
        init() {
            //绑定年级
            let now = new Date();
            let currentYear = now.getFullYear(),
                minYear = currentYear - 10;
            for (let grade = currentYear + 1; grade > minYear; grade--) {
                let obj = { label: grade, value: grade };
                this.options.grade.push(obj);
            }
            let data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: ["X_YX"]
            };
            queryDic(data).then(res => {
                if (res.code == 200) {
                    UTILS.fillSelect(
                        {
                            college: "X_YX"
                        },
                        res.data,
                        this.options
                    );
                }
            });
        },
        initPlanPermissionData() {
            if (!this.$checkMinor()) return;
            let params = {
                grade: this.queryForm.grade,
                advancedLevelCode: this.queryForm.advancedLevel,
                startTime: this.queryForm.startTime,
                endTime: this.queryForm.endTime,
                pageNum: this.page.pageNum,
                pageSize: this.page.pageSize
            };
            queryCulturePlanPermission(params).then(res => {
                if (res.code == 200) {
                    const dataList = res.data;
                    if (dataList.list && dataList.list.length > 0) {
                        dataList.list.forEach(e => {
                            e.startTime = !e.startTime
                                ? null
                                : INDEX.parseTime(e.startTime);
                            e.endTime = !e.endTime
                                ? null
                                : INDEX.parseTime(e.endTime);
                        });
                    } else {
                        dataList.list = [];
                    }

                    this.tableData.list = dataList.list;
                    this.tableData.total_ = res.data.total_;
                }
            });
        },
        handleSelectionChange(val) {
            this.selectData = val;
        },
        reset() {
            this.queryForm.grade = "";
            this.queryForm.advancedLevel = "";
            this.queryForm.startTime = "";
            this.queryForm.endTime = "";
            this.initPlanPermissionData();
        },
        //编辑权限
        editPermission(row) {
            if (this.$refs.postForm) this.$refs.postForm.resetFields();
            this.postForm.id = row.id;
            this.postForm.grade = row.grade + "";
            this.postForm.advancedLevel = row.advancedLevelCode;
            this.postForm.startTime = moment(row.startTime);
            this.postForm.endTime = moment(row.endTime);
            this.dialogTitle = "编辑权限";
            this.showDialog = true;
        },
        showAddDialog() {
            if (!this.$checkMinor()) return;
            this.postForm = {
                grade: "",
                advancedLevel: "",
                startTime: "",
                endTime: "",
                id: null
            };
            if (this.$refs.postForm) this.$refs.postForm.resetFields();
            this.dialogTitle = "创建计划开放权限";
            this.showDialog = true;
        },
        //删除权限
        deletePermission(row) {
            let params = {
                id: row.id
            };
            this.$confirm("您确定要删除吗？", "删除", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    deleteCulturePlanPermission(params).then(res => {
                        if (res.code == 200) {
                            this.$message({
                                type: "success",
                                message: "删除成功!"
                            });
                            this.initPlanPermissionData();
                        }
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除"
                    });
                });
        },
        //取消新增
        cancel() {
            this.showDialog = false;
        },
        //保存权限
        save() {
            this.$refs.postForm.validate(valid => {
                if (valid) {
                    if (this.postForm.id == null) {
                        //新增
                        let params = {
                            grade: this.postForm.grade,
                            advancedLevelCode: this.postForm.advancedLevel,
                            startTime: moment(
                                this.postForm.startTime
                            ).valueOf(),
                            endTime: moment(this.postForm.endTime).valueOf()
                        };
                        insertCulturePlanPermission(params).then(res => {
                            if (res.code == 200) {
                                this.$message({
                                    message: "新增成功",
                                    type: "success"
                                });
                                this.showDialog = false;
                                this.initPlanPermissionData();
                            }
                        });
                    } else {
                        let params = {
                            id: this.postForm.id,
                            grade: this.postForm.grade,
                            advancedLevelCode: this.postForm.advancedLevel,
                            startTime: moment(
                                this.postForm.startTime
                            ).valueOf(),
                            endTime: moment(this.postForm.endTime).valueOf()
                        };
                        modifyCulturePlanPermission(params).then(res => {
                            if (res.code == 200) {
                                this.$message({
                                    message: "修改成功",
                                    type: "success"
                                });
                                this.showDialog = false;
                                this.initPlanPermissionData();
                            }
                        });
                    }
                } else {
                    return false;
                }
            });
        },
        //查询数据
        searchData() {
            this.initPlanPermissionData();
        },
        //批量删除
        batchDeleteAuthPushData() {
            if (!this.$checkMinor()) return;
            if (this.selectData.length == 0) {
                this.$message.warning("请先选择需要删除的数据。");
                return;
            }
            let authPushIds = [];
            this.selectData &&
                this.selectData.forEach(e => {
                    authPushIds.push(e.id);
                });
            let params = {
                authPushId: authPushIds
            };
            this.$confirm("您确定要删除吗？", "删除", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    batchDeleteCulturePlanPermission(params).then(res => {
                        if (res.code == 200) {
                            this.$message({
                                type: "success",
                                message: "删除成功!"
                            });
                            this.initPlanPermissionData();
                        }
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除"
                    });
                });
        }
    }
};
</script>
<style lang="scss" scoped>
</style>